package com.chengqj.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.chengqj.model.TArticleModel;
import com.chengqj.pojo.TArticle;
import com.chengqj.pojo.User;
import com.chengqj.service.IMainService;
import com.chengqj.util.DateUtil;

@Controller
@RequestMapping("/main")
public class MainController {
	@Resource
	private IMainService mainService;

	private static final String defaultImagePath = "/home/static/images/";
	private static final String defaultImageUrl = "/static/images/";

	@RequestMapping("/showUser")
	public String toIndex(HttpServletRequest request, Model model) {
		int userId = Integer.parseInt(request.getParameter("id"));
		User user = this.mainService.getUserById(userId);
		model.addAttribute("user", user);
		return "showUser";
	}

	@RequestMapping
	public String index(ModelMap modelMap, HttpServletRequest request,
			@RequestParam(required = false) Integer page) {
		TArticle ta = new TArticle();
		List<TArticle> object = mainService.selectByType(ta);
		initMap(modelMap, page, object, "main");
		List<TArticleModel> list = (List<TArticleModel>) modelMap.get("list");
		List<TArticleModel> indexList = new ArrayList<TArticleModel>();
		for (int i = 0; i < 6 && i < list.size(); i++) {
			indexList.add(list.get(i));
		}
		modelMap.put("indexList", indexList);
		return "/index.jsp";
	}

	@RequestMapping("/manlifeType")
	public String manlifeType(ModelMap modelMap, HttpServletRequest request,
			@RequestParam(required = false) String type,
			@RequestParam(required = false) Integer page) {
		TArticle ta = new TArticle();
		ta.setType(1);
		ta.setSmallType(Integer.parseInt(type));
		List<TArticle> object = mainService.selectByType(ta);
		initMap(modelMap, page, object, "main/manlifeType");
		return "/manlife.jsp";
	}

	@RequestMapping("/manlife")
	public String manLife(ModelMap modelMap, HttpServletRequest request,
			@RequestParam(required = false) Integer page) {
		TArticle ta = new TArticle();
		ta.setType(1);
		List<TArticle> object = mainService.selectByType(ta);
		initMap(modelMap, page, object, "main/manlife");
		return "/manlife.jsp";
	}

	@RequestMapping("/context")
	public String xwzjcontext(ModelMap modelMap, HttpServletRequest request,
			@RequestParam(required = false) Integer id) {
		TArticle object = mainService.getArticleById(id);
		modelMap.put("model", TArticleModel.createTArticleModel(object));
		int type = object.getType();
		if (type == 1) {
			TArticle ta = new TArticle();
			ta.setType(1);
			List<TArticle> talist = mainService.selectByType(ta);
			List<TArticleModel> list = new ArrayList<TArticleModel>();
			int i = 0;
			for (TArticle obj : talist) {
				if (i < 6) {
					list.add(TArticleModel.createTArticleModel(obj));
					i = i + 1;
				} else {
					break;
				}
			}
			modelMap.put("list", list);
			return "/manlifecontext.jsp";
		} else if (type == 3) {
			TArticle ta = new TArticle();
			ta.setType(3);
			List<TArticle> talist = mainService.selectByType(ta);
			List<TArticleModel> list = new ArrayList<TArticleModel>();
			int i = 0;
			for (TArticle obj : talist) {
				if (i < 6) {
					list.add(TArticleModel.createTArticleModel(obj));
					i = i + 1;
				} else {
					break;
				}
			}
			modelMap.put("list", list);
			return "/xwzjcontext.jsp";
		}
		return "main";
	}

	@RequestMapping("/xwzjType")
	public String xwzjType(ModelMap modelMap, HttpServletRequest request,
			@RequestParam(required = false) String type,
			@RequestParam(required = false) Integer page) {
		TArticle ta = new TArticle();
		ta.setType(3);
		ta.setSmallType(Integer.parseInt(type));
		List<TArticle> object = mainService.selectByType(ta);
		initMap(modelMap, page, object, "main/xwzjType");
		return "/xuewuzhijing.jsp";
	}

	@RequestMapping("/xuewuzhijing")
	public String xuewuzhijing(ModelMap modelMap, HttpServletRequest request,
			@RequestParam(required = false) Integer page) {
		TArticle ta = new TArticle();
		ta.setType(3);
		List<TArticle> object = mainService.selectByType(ta);
		initMap(modelMap, page, object, "main/xuewuzhijing");
		return "/xuewuzhijing.jsp";
	}

	@RequestMapping("/suiyansuiyu")
	public String suiyansuiyu(ModelMap modelMap, HttpServletRequest request,
			@RequestParam(required = false) Integer page) {
		TArticle ta = new TArticle();
		ta.setType(2);
		List<TArticle> object = mainService.selectSySy();
		initMap(modelMap, page, object, "main/suiyansuiyu");
		return "/suiyansuiyu.jsp";
	}

	private void initMap(ModelMap modelMap, Integer page,
			List<TArticle> object, String url) {
		List<TArticleModel> list = new ArrayList<TArticleModel>();
		int pre = 0;
		int end = 0;
		if (page == null || page == 0) {
			page = 0;
			end = page + 2;
		} else {
			pre = page - 1;
			end = page + 1;
			page = page - 1;
		}
		for (int i = page * 6; i < object.size() && i < page * 6 + 6; i++) {
			list.add(TArticleModel.createTArticleModel(object.get(i)));
		}
		String content = "";
		int totalPage = object.size() / 6;
		if (object.size() % 6 > 0) {
			totalPage = totalPage + 1;
		}
		for (int i = 0; i < totalPage; i++) {
			int temp = i + 1;
			content = content + "<a href=\"" + url + "?page=" + temp + "\">"
					+ temp + "</a>";
		}

		if (page != 0) {
			content = "<a href=\"" + url + "?page=0\"><<</a><a href=\"" + url
					+ "?page=" + pre + "\"><</a>" + content;
		} else if (totalPage != 1 && page != totalPage) {
			content = content + "<a href=\"" + url + "?page=" + end
					+ "\">></a><a href=\"" + url + "?page=" + totalPage
					+ "\">>></a>";
		}
		content = "<a title=\"Total record\"><b>" + object.size() + "</b> </a>"
				+ content;
		if (object.size() > 6) {
			modelMap.put("content", content);
		}
		modelMap.put("list", list);
	}

	@ResponseBody
	@RequestMapping(value = "/insertImage", method = RequestMethod.POST)
	public Map<String, String> insertImage(
			@RequestParam("filePath") MultipartFile filePath,
			HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> map = new HashMap<String, String>();
		response.setContentType("text/html;charset=UTF-8");
		String fileName = DateUtil.getYYYYMMDDHHMMSS(new Date());
		String localPath = "";
		try {
			InputStream fis = filePath.getInputStream();
			localPath = defaultImagePath + fileName
					+ filePath.getOriginalFilename();
			writeFile(fis, localPath);
		} catch (IOException e) {
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.put("result", "success");
		map.put("localPath",
				defaultImageUrl + fileName + filePath.getOriginalFilename());
		return map;
	}

	@RequestMapping(value = "/insertContent", method = RequestMethod.POST)
	public void insertContent(String myEditor, String title, String selectType,
			String smallType, String localPath, HttpServletResponse response) {
		Map<String, String> map = new HashMap<String, String>();
		TArticle record = new TArticle();
		record.setAuthor("三台");
		int index = myEditor.indexOf("</p>");
		if (index < 1) {
			record.setKeyContext(myEditor);
		} else {
			record.setKeyContext(myEditor.substring(0, index + "</p>".length()));
		}
		record.setContext(myEditor);
		record.setCreateDate(new Date());
		record.setPublishDate(new Date());
		try {
			record.setSmallType(Integer.parseInt(smallType));
		} catch (Exception e) {
		}
		try {
			record.setType(Integer.parseInt(selectType));
		} catch (Exception e) {
			record.setType(1);
		}

		record.setTitle(title);
		record.setInImageUrl(localPath);
		mainService.insert(record);
		map.put("result", "success");
		try {
			response.sendRedirect("/main");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/upload")
	public String upload(HttpServletRequest request,
			HttpServletResponse response) {
		// 得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
		File file = new File("d:");
		// 判断上传文件的保存目录是否存在
		if (!file.exists() && !file.isDirectory()) {
			// 创建目录
			file.mkdir();
		}
		// 消息提示
		String message = "";
		try {
			// 使用Apache文件上传组件处理文件上传步骤：
			// 1、创建一个DiskFileItemFactory工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 2、创建一个文件上传解析器
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 解决上传文件名的中文乱码
			upload.setHeaderEncoding("UTF-8");
			// 3、判断提交上来的数据是否是上传表单的数据
			if (!ServletFileUpload.isMultipartContent(request)) {
				// 按照传统方式获取数据
				return "";
			}
			// 4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
			List<FileItem> list = upload.parseRequest(request);
			for (FileItem item : list) {
				// 如果fileitem中封装的是普通输入项的数据
				if (item.isFormField()) {
					String name = item.getFieldName();
					// 解决普通输入项的数据的中文乱码问题
					String value = item.getString("UTF-8");
					// value = new String(value.getBytes("iso8859-1"),"UTF-8");
					System.out.println(name + "=" + value);
				} else {// 如果fileitem中封装的是上传文件
					// 得到上传的文件名称，
					String filename = item.getName();
					System.out.println(filename);
					if (filename == null || filename.trim().equals("")) {
						continue;
					}
					// 注意：不同的浏览器提交的文件名是不一样的，有些浏览器提交上来的文件名是带有路径的，如：
					// c:\a\b\1.txt，而有些只是单纯的文件名，如：1.txt
					// 处理获取到的上传文件的文件名的路径部分，只保留文件名部分
					filename = filename
							.substring(filename.lastIndexOf("\\") + 1);
					// 获取item中的上传文件的输入流
					InputStream in = item.getInputStream();
					// 创建一个文件输出流
					FileOutputStream out = new FileOutputStream("d:" + "\\"
							+ filename);
					// 创建一个缓冲区
					byte buffer[] = new byte[1024];
					// 判断输入流中的数据是否已经读完的标识
					int len = 0;
					// 循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
					while ((len = in.read(buffer)) > 0) {
						// 使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\"
						// + filename)当中
						out.write(buffer, 0, len);
					}
					// 关闭输入流
					in.close();
					// 关闭输出流
					out.close();
					// 删除处理文件上传时生成的临时文件
					item.delete();
					message = "文件上传成功！";
				}
			}
		} catch (Exception e) {
			message = "文件上传失败！";
			e.printStackTrace();

		}
		request.setAttribute("message", message);

		return "";
	}

	private void writeFile(InputStream fis, String filePath) throws Exception {
		FileOutputStream fs = new FileOutputStream(filePath);
		byte[] buffer = new byte[1024 * 1024];
		// int bytesum = 0;
		int byteread = 0;
		while ((byteread = fis.read(buffer)) != -1) {
			// bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		fis.close();
	}

}
